package com.aaa.system.service.impl;

import com.aaa.common.entity.Menu;
import com.aaa.common.entity.User;
import com.aaa.common.util.WebUtil;
import com.aaa.common.vo.Result;
import com.aaa.system.dao.MenuDao;
import com.aaa.system.service.MenuService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: aaa-hospital-parent
 * @description:
 * @author: 闫克起
 * @create: 2024-05-21 16:51
 **/
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Result<List<Menu>> findByUserId() {
        String token = WebUtil.getRequest().getHeader("token");
        String s = redisTemplate.opsForValue().get("user:login:" + token);
        User user = JSON.parseObject(s, User.class);
        List<Menu> menus=menuDao.queryByUserId(user.getUserId());
        //层级
        List<Menu> firsts=menus.stream().filter(item->item.getParentId().equals(0L)).collect(Collectors.toList());
        //查询一级菜单下的子菜单
        for(Menu f:firsts){
             f.setChildren(getChildren(f.getMenuId(),menus));
        }
        return new Result<>(2000,"查询左侧菜单成功",firsts);
    }

    private List<Menu> getChildren(Long menuId, List<Menu> menus) {
        List<Menu> children=new ArrayList<>();
        for(Menu m:menus){
             if(m.getParentId().equals(menuId)){
                 children.add(m);
             }
        }
        for(Menu c:children){
             c.setChildren(getChildren(c.getMenuId(),menus));
        }
        return children;
    }
}
